<template>
  <div>
    <el-form :model="groupQuery" inline ref="queryFormRef">
      <el-form-item label="分类" prop="categoryId">
        <el-cascader v-model="groupQuery.categoryId" :options="categoryList" clearable @focus="getAllCategory"
                     :show-all-levels="false"
                     :props="showProps"/>
      </el-form-item>
      <el-form-item>
        <el-button @click="getAttrGroupPage" icon="Search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="queryFormRef.resetFields()" type="primary" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="addDialog = true" size="small">新增分组</el-button>
    </div>
    <el-table :data="attrGroupPage.list" v-loading="loading">
      <el-table-column prop="categoryId" label="编号" width="100"/>
      <el-table-column prop="groupName" label="分组名" width="180"/>
      <el-table-column prop="description" label="描述" width="180"/>
      <el-table-column prop="categoryId" label="所属三级分类"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" @click="assoAttrAttrgroup(scope.row.groupId)">关联</el-button>
          <el-divider direction="vertical"/>
          <el-button size="small" type="warning" @click="openUpdate(scope.row)">修改</el-button>
          <el-divider direction="vertical"/>
          <el-button size="small" type="danger" @click="openDel(scope.row.groupId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--新增对话框-->
    <el-dialog v-model="addDialog" title="新增分组" width="30%" @close="fromRef.resetFields()">
      <el-form :model="attrGroupForm" size="large" label-width="80px" label-position="left" ref="fromRef"
               :rules="rules">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="attrGroupForm.groupName" placeholder="请输入分组的名称"/>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader v-model="attrGroupForm.categoryId" :options="categoryList" clearable @focus="getAllCategory"
                       :show-all-levels="false"
                       :props="showProps"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="attrGroupForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="attrGroupForm.description" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="submitGroup(fromRef)">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="assoAttrAttrgroupDialog"
        title="分组属性关联列表"
        width="700"
        draggable
    >
      <el-form inline :model="attributeQuery" ref="attributeQueryRef">
        <el-form-item prop="categoryId">
          <el-cascader v-model="attributeQuery.categoryId" :options="categoryList" clearable @focus="getAllCategory"
                       placeholder="请选择分类"
                       :show-all-levels="false"
                       :props="showProps"/>
        </el-form-item>
        <el-form-item prop="showAll">
          <el-select
              v-model="attributeQuery.showAll"
              placeholder="请选择"
              size="large"
              style="width: 100px"
          >
            <el-option label="未关联" :value="false"/>
            <el-option label="所有" :value="true"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="getAttributePage">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="attributeQueryRef.resetFields()" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="attributePage.list" ref="multipleTableRef" row-key="attributeId"
                @selection-change="handleSelectionChange" v-loading="attributeLoading">
        <el-table-column type="selection" width="55" :reserve-selection="true"/>
        <el-table-column prop="attrName" label="属性名" width="100"/>
        <el-table-column prop="attrType" label="属性类型" width="100"/>
        <el-table-column prop="searchType" label="是否可以搜索" width="150"/>
        <el-table-column prop="valueSelect" label="可选值列表" width="150"/>
      </el-table>
      <el-pagination layout="prev, pager, next" :total="attributePage.total"
                     v-model:current-page="attributeQuery.pageNum"
                     v-model:page-size="attributeQuery.pageSize"/>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="assoAttrAttrgroupDialog = false">取消</el-button>
        <el-button type="primary" @click="assoSubmit">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {nextTick, onMounted, reactive, ref, watch} from 'vue'
import {
  reqGetSpuCategoryTreeList,
  reqCreateSkuAttrGroup,
  reqGetSkuAttrGroupPage,
  reqGetSkuAttrGroupById,
  reqDeleteSkuAttrGroup,
  reqGetSkuAttributePageByGroup,
  reqSkuAttributeGroupAssociated
} from "@/api/serve/re-market";
import type {SkuAttributeGroup, SkuAttribute} from '@/api/serve/re-market/type'
import type {FormInstance} from "element-plus";

let fromRef = ref<FormInstance>()//表单清空等需要的属性
let queryFormRef = ref<FormInstance>()
let attributeQueryRef = ref()
let attrGroupPage = reactive({
  pageNum: 1,
  total: 0,
  list: []
})
let attributePage = reactive({
  pageNum: 1,
  total: 0,
  list: []
})
let groupQuery = reactive({
  categoryId: '',
  pageNum: 1,
  pageSize: 10
})
let attributeQuery = reactive({
  showAll: false,
  attributeType: 1,
  categoryId: '',
  attrType: '',//分组不能是销售属性
  groupId: '',
  pageNum: 1,
  pageSize: 4
})
let multipleTableRef = ref()
let loading = ref(true)
let attributeLoading = ref(true)
let addDialog = ref(false)
let categoryList = ref([])
/*属性分组与属性关联数据*/
let assoAttrAttrgroupDialog = ref(false)
//属性与分组的关联
let attrGroupAsso = reactive({
  attributeIds: [],
  groupId: ''
})
let attrGroupForm = reactive<SkuAttributeGroup>({
  groupName: '',
  sort: 0,
  description: '',
  categoryId: null
})
let showProps = reactive({
  label: 'name',
  value: 'categoryId',
  children: 'children',
  emitPath: false
})


let getAllCategory = () => {
  reqGetSpuCategoryTreeList().then(res => {
    categoryList.value = res.data
  })
}

let getAttributePage = () => {
  reqGetSkuAttributePageByGroup(attributeQuery).then(res => {
    Object.assign(attributePage, res.data)
    //默认选中
    console.log('attributePage.list', attributePage.list)
    nextTick(() => {
      if (Array.isArray(attributePage.list)) {
        attributePage.list.forEach(row => {
          if (row.isAssociated) {
            multipleTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
    })
  }).finally(() => {
    attributeLoading.value = false
  })
}
const handleSelectionChange = (val: SkuAttribute[]) => {
  attrGroupAsso.attributeIds = val.map(item => item.attributeId)
}

let getAttrGroupPage = () => {
  reqGetSkuAttrGroupPage(groupQuery).then(res => {
    Object.assign(attrGroupPage, res.data)
    loading.value = false
  })
}

const submitGroup = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await reqCreateSkuAttrGroup(attrGroupForm)
      await getAttrGroupPage()
      addDialog.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

function assoAttrAttrgroup(groupId) {
  attrGroupAsso.groupId = groupId
  assoAttrAttrgroupDialog.value = true
  attributeQuery.groupId = groupId
  getAttributePage()
}

/**
 * 关联分组
 */
function assoSubmit() {
  reqSkuAttributeGroupAssociated(attrGroupAsso).then(res => {
    getAttrGroupPage()
  })
  assoAttrAttrgroupDialog.value = false
}

onMounted(() => {
  getAttrGroupPage()
})

function openDel(groupId) {
  ElMessageBox.confirm(
      `你确定要删除分组吗？`,
      '警告',
      {
        provides: undefined,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        reqDeleteSkuAttrGroup(groupId)
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消成功',
        })
      })
}

/*表单校验规则*/
let rules = reactive({
  groupName: [
    {required: true, message: '分组名称不能为空', trigger: 'blur'}
  ],
  categoryId: [
    {required: true, message: '所属三级分类不能为空', trigger: 'blur'}
  ]
})
watch([() => attributeQuery.pageNum], () => {
  getAttributePage()
})
</script>

<style scoped>

</style>
